/*
 * Project Name spring-boot-tools
 * File Name JobServiceImpl
 * Package Name com.huxiaosu.tools.quartz.service.impl
 * Create Time 2024/7/29
 * Create by name：liujie
 */
package com.huxiaosu.tools.quartz.service.impl;

import com.huxiaosu.tools.mybatis.base.service.impl.BaseServiceImpl;
import com.huxiaosu.tools.quartz.dto.JobDetailsDto;
import com.huxiaosu.tools.quartz.entity.JobDetails;
import com.huxiaosu.tools.quartz.mapper.JobDetailsMapper;
import com.huxiaosu.tools.quartz.mapper.JobLogMapper;
import com.huxiaosu.tools.quartz.service.JobService;
import com.huxiaosu.tools.quartz.task.CallBackTask;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Future;

/**
 * Description
 *
 * @author liujie
 * @date 2024/7/29 13:24
 */
@Slf4j
@Service
public class JobServiceImpl extends BaseServiceImpl<JobDetailsMapper, JobDetailsDto, JobDetails> implements JobService {
    private static final Map<Integer,Future<?>> futureMap = new HashMap<>();
    @Autowired
    private JobLogMapper jobLogMapper;
    @Autowired
    private ThreadPoolTaskScheduler threadPoolTaskScheduler;


    @Override
    @Transactional
    public void startOrStopJob(Integer jobId) {
        JobDetails jobDetails = super.baseDao.selectById(jobId);
        if(jobDetails == null){
            return;
        }
        Integer jobStatus = jobDetails.getJobStatus();
        if(jobStatus == 0 ){
            // 启动
            jobDetails.setJobStatus(1);
            start(jobDetails);
        }else{
            jobDetails.setJobStatus(0);
        }
        super.baseDao.updateById(jobDetails);

    }
    public void start(JobDetails job) {
        // 调用线程，启动任务
        CronTrigger trigger = new CronTrigger(job.getJobCorn());
        CallBackTask callBackTask = new CallBackTask(job, jobLogMapper);
        Future<?> future = threadPoolTaskScheduler.schedule(callBackTask, trigger);
        job.setJobStatus(1);

        futureMap.put(job.getId(),future);

    }

    public void stop(JobDetails job) {
        Integer jobId = job.getId();
        Future<?> future = futureMap.get(jobId);
        if (future != null) {
            future.cancel(false);
        }

    }
}